GameplaySubSystem实现

维护 SubSystem 的解决方案;

在维护各个业务时,经常需要将 Manager 下面再拆出若干个子系统,需要一种快捷的方法快速扩展出一套 SubSystem 系统:

  1. 基本结构:由 Manager 持有 SubSystemCollection ,Collection 中持有若干个继承于 SubSystemBase 的自定义 SubSystem;
  2. 同步方案:当 Manager 是 Actor / ActorComponent 且 Collection 中的 SubSystem 需要同步数据时,提供 SubSystem 的同步策略,保证双端统一;

基本结构

classDiagram
    direction LR

    IGameplaySubSystemCollectionOwnerInterface <|-- Manager
    class IGameplaySubSystemCollectionOwnerInterface {
        +GetSubSystemCollectionPtrs()
        +GetSubSystemCollectionPtr(UClass* InClass)
    }

    Manager ..* FGameplaySubSystemCollection
    class Manager {
        SubSystemCollections : FGameplaySubSystemCollection~UGameplaySubSystem~
    }

    class FGameplaySubSystemCollectionBase {
        Outer : TWeakObjectPtr~UObject~
        SubSystemMap : TMap~UClass*, TStrongObjectPtr[UGameplaySubSystemBase]~
        BaseType : UClass*

        +Initialize(InOuter, bCreatedDerivedClasses)
        +Initialize(InOuter, InSubSystemClasses)
        +SetOuter(InOuter)
        +Uninitialize()
        +Tick()

        +AddSubSystem(SubSystem)
        +RemoveSubSystem(SubSystem)
        +GetSubSystem(SubSystemClass)
        +GetSubSystems(SubSystemClass)
        +ReplicateSubSystems(Channel, Bunch, RepFlags)
        # AddReplicatedSubSystem(SubSystem)
        # RemoveReplicatedSubSystem(SubSystem)

        OnCreatedFromReplication : FCreatedFromReplication
    }

    FGameplaySubSystemCollectionBase <|-- FGameplaySubSystemCollection
    FGameplaySubSystemCollectionBase ..> UGameplaySubSystemBase
    class FGameplaySubSystemCollection {
        FGameplaySubSystemCollection()
        +GetSubSystem~T~()
        +GetSubSystems~T~()
    }

    IInterface_ActorSubobject <|-- UGameplaySubSystemBase
    class IInterface_ActorSubobject {
        +OnCreatedFromReplication()
        +OnDestroyedFromReplication()
    }

    class UGameplaySubSystemBase {
        LastTickTimeStamp : double
        IsCreatedFromReplication : bool

        +Initialize()
        +Uninitialize()
        # OnInitialized()
        # OnUninitialized()

        +Tick()
        # OnTick(DeltaTime)
        # GetTickInternal()
        # GetCurrentTimeStamp()

        +IsSupportedForNetworking()
        +GetOwnerActor()
        +CallRemoteFunction(...)
        +GetFunctionCallspace(...)
        +OnCreatedFromReplication()
        +OnDestroyedFromReplication()
    }

    UGameplaySubSystemBase <|-- UGameplaySubSystem
    class UGameplaySubSystem {
        # OnInitialized()
        # OnUninitialized()
        # OnTick(DeltaTime)
        # GetTickInternal()
    }

注:相比早期版本,现在的实现做了几处调整:

  • 生命周期方法名由 Init / Uninit 改为 Initialize / Uninitialize,与 UE 内置 USubsystem 保持一致;
  • 时间戳由 float LastTickTime 改为 double LastTickTimeStamp,GetWorldTimeNow 改为 GetCurrentTimeStamp,统一走 GameState->GetServerWorldTimeSeconds();
  • 同步路径在保留 ReplicateSubobjects 旧通道的同时,接入了 UE5 的 bReplicateUsingRegisteredSubObjectList:在 AddSubSystem / RemoveSubSystem 内自动 AddReplicatedSubObject / DestroyReplicatedSubObjectOnRemotePeers,原文 TODO 中"UE4 没有动态 Remove"的限制已不存在;
  • Collection 提供基于 SubSystemClass 的运行时 Get 接口(支持 IsChildOf 过滤),并通过 DECLARE_GAMEPLAYSUBSYSTEM_ACCESSORS_BY_NAME 让宿主能定制访问器名字。

Manager

由 Manager 持有对应类型的 SubSystemCollection,主动调用 Initialize、Uninitialize、Tick 。

同时,为了后续的同步, Manager 需要重载 IGameplaySubSystemCollectionOwnerInterface 的 GetSubSystemCollectionPtrs,用于找到对应的 Collection(如果不需要同步,也可以不实现);

一个 Manager 可能同时持有多个 SubSystemCollection,所以这里返回的是数组。

提供两个宏,方便地为宿主注入访问器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#define DECLARE_GAMEPLAYSUBSYSTEM_ACCESSORS_BY_NAME(Name, BaseClass, SubSystemCollections) \
BaseClass* Get##Name(UClass* SubSystemClass) const \
{ \
return SubSystemCollections.GetSubSystem(SubSystemClass); \
} \
template<class T = BaseClass> \
requires (TIsDerivedFrom<T, BaseClass>::Value == true) \
T* Get##Name() const \
{ \
return SubSystemCollections.GetSubSystem<T>(); \
} \
TArray<BaseClass*> Get##Name##s(UClass* SubSystemClass = nullptr) const \
{ \
return SubSystemCollections.GetSubSystems(SubSystemClass); \
} \
template<class T = BaseClass> \
requires (TIsDerivedFrom<T, BaseClass>::Value == true) \
TArray<T*> Get##Name##s() const \
{ \
return SubSystemCollections.GetSubSystems<T>(); \
}

#define DECLARE_GAMEPLAYSUBSYSTEM_ACCESSORS(BaseClass, SubSystemCollections) \
DECLARE_GAMEPLAYSUBSYSTEM_ACCESSORS_BY_NAME(SubSystem, BaseClass, SubSystemCollections)

_BY_NAME 版本能在同一个 Manager 上同时挂多个不同业务的 Collection,避免同名冲突。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// IGameplaySubSystemCollectionOwnerInterface.h

UINTERFACE(BlueprintType, Blueprintable)
class UGameplaySubSystemCollectionOwnerInterface : public UInterface
{
GENERATED_BODY()
};

class IGameplaySubSystemCollectionOwnerInterface
{
GENERATED_BODY()

public:
virtual TArray<FGameplaySubSystemCollectionBase*> GetSubSystemCollectionPtrs() = 0;

public:
FGameplaySubSystemCollectionBase* GetSubSystemCollectionPtr(UClass* InClass);
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// IGameplaySubSystemCollectionOwnerInterface.cpp

FGameplaySubSystemCollectionBase* IGameplaySubSystemCollectionOwnerInterface::GetSubSystemCollectionPtr(UClass* InClass)
{
auto CollectionPtrs = GetSubSystemCollectionPtrs();

for (auto CollectionPtr : CollectionPtrs)
{
if (CollectionPtr != nullptr && InClass->IsChildOf(CollectionPtr->GetBaseType()))
{
return CollectionPtr;
}
}

return nullptr;
}

宿主侧的接入示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Manager.h
public:
DECLARE_GAMEPLAYSUBSYSTEM_ACCESSORS_BY_NAME(SubSystemA, USubSystemBase_A, SubSystemCollection_A);
DECLARE_GAMEPLAYSUBSYSTEM_ACCESSORS_BY_NAME(SubSystemB, USubSystemBase_B, SubSystemCollection_B);

virtual TArray<FGameplaySubSystemCollectionBase*> GetSubSystemCollectionPtrs() override
{
return { &SubSystemCollection_A, &SubSystemCollection_B };
}

private:
FGameplaySubSystemCollection<USubSystemBase_A> SubSystemCollection_A;
FGameplaySubSystemCollection<USubSystemBase_B> SubSystemCollection_B;

// Manager.cpp 在合适时机:
SubSystemCollection_A.Initialize(this);
SubSystemCollection_A.Uninitialize();
SubSystemCollection_A.Tick();

SubSystemCollection

SubSystemCollection 负责收集与管理所有的 SubSystem。

在 SubSystemCollectionBase 中,提供一个 BaseClass,这个 BaseClass 由对应的 SubSystemCollection 在初始化的时候传入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template<typename TBaseType>
struct FGameplaySubSystemCollection : FGameplaySubSystemCollectionBase
{
using Super = FGameplaySubSystemCollectionBase;
static_assert(TIsDerivedFrom<TBaseType, UGameplaySubSystemBase>::Value, "TBaseType must inherit from UGameplaySubSystemBase");

FGameplaySubSystemCollection() : FGameplaySubSystemCollectionBase(TBaseType::StaticClass())
{
}
};

FGameplaySubSystemCollectionBase::FGameplaySubSystemCollectionBase(UClass* InBaseType)
: BaseType(InBaseType)
{
check(BaseType);
}

提供两种 Initialize 方法:

  1. 根据 BaseClass,找到所有继承于该类的 Class 创建 SubSystem ;
  2. 指定 SubSystemClasses 进行创建 SubSystem ;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void FGameplaySubSystemCollectionBase::Initialize(UObject* InOuter, bool bCreatedDerivedClasses)
{
if (!SetOuter(InOuter)) return;

if (bCreatedDerivedClasses)
{
TArray<UClass*> SubSystemClasses;
GetDerivedClasses(BaseType, SubSystemClasses, true);
AddSubSystemByClasses( SubSystemClasses );
}
}

void FGameplaySubSystemCollectionBase::Initialize(UObject* InOuter, const TArray<UClass*>& InSubSystemClasses)
{
if (!SetOuter(InOuter)) return;
AddSubSystemByClasses(InSubSystemClasses);
}

bool FGameplaySubSystemCollectionBase::SetOuter(UObject* InOuter)
{
if (Outer.IsValid()) return false; // already initialized
if (!IsValid(InOuter)) return false; // invalid Outer
Outer = InOuter;
return true;
}

用 TMap<UClass*, TStrongObjectPtr<UGameplaySubSystemBase>> SubSystemMap 将所有的 SubSystem 实例保存下来。

由于期望 FGameplaySubSystemCollection 可以在编译期决定类型,使用了 template<typename TBaseType> ,这也导致无法走 UHT 的反射挂上 UPROPERTY 标记来保证其生命周期。所以这里用 TStrongObjectPtr 来手动持有 SubSystem,保证不会被 GC;缺点是 TStrongObjectPtr 的 Reset 校验其必须 InGameThread:

1
2
3
4
5
6
7
8
9
explicit FInternalReferenceCollector(const volatile UObject* InObject) : Object(InObject)
{
check(IsInGameThread());
}

virtual ~FInternalReferenceCollector()
{
check(IsInGameThread() || IsInGarbageCollectorThread());
}

备选方案是 AddToRoot / RemoveFromRoot + TWeakObjectPtr 记录,但相对 TStrongObjectPtr 心智负担更大,目前实现统一走 TStrongObjectPtr。

完整实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// FGameplaySubSystemCollection.h

struct GAMEPLAYSUBSYSTEM_API FGameplaySubSystemCollectionBase
{
public:
FGameplaySubSystemCollectionBase(UClass* InBaseType);
UClass* GetBaseType() const;

// SubSystem Lifetime
void Initialize(UObject* InOuter, bool bCreatedDerivedClasses = true);
void Initialize(UObject* InOuter, const TArray<UClass*>& InSubSystemClasses);
bool SetOuter(UObject* InOuter);
void Uninitialize();
void Tick();

// Add / Remove
TArray<UGameplaySubSystemBase*> AddSubSystemByClasses(const TArray<UClass*>& SubSystemClasses);
UGameplaySubSystemBase* AddSubSystemByClass(UClass* SubSystemClass);
void AddSubSystem(UGameplaySubSystemBase* SubSystem);
void RemoveSubSystemByClass(UClass* SubSystemClass);
void RemoveSubSystem(UGameplaySubSystemBase* SubSystem);

// Getter
UGameplaySubSystemBase* GetSubSystem(TSubclassOf<UGameplaySubSystemBase> SubSystemClass) const;
TArray<UGameplaySubSystemBase*> GetSubSystems(TSubclassOf<UGameplaySubSystemBase> SubSystemClass = nullptr) const;

protected:
UGameplaySubSystemBase* GetSubSystemInternal(UClass* SubSystemClass) const;
TArray<UGameplaySubSystemBase*> GetSubSystemsInternal(UClass* SubSystemClass) const;

// Replicate
public:
// 当宿主未启用 bReplicateUsingRegisteredSubObjectList 时,由宿主在 ReplicateSubObjects 中主动调用
bool ReplicateSubSystems(class UActorChannel* Channel, class FOutBunch* Bunch, struct FReplicationFlags* RepFlags);
private:
void AddReplicatedSubSystem(UGameplaySubSystemBase* SubSystem);
void RemoveReplicatedSubSystem(UGameplaySubSystemBase* SubSystem);

// Delegate
public:
DECLARE_MULTICAST_DELEGATE_TwoParams(FCreatedFromReplication, UClass* /*Type*/, UGameplaySubSystemBase* /*Instance*/);
FCreatedFromReplication OnCreatedFromReplication;

private:
TWeakObjectPtr<UObject> Outer = nullptr;
UClass* BaseType = nullptr;
TMap<UClass*, TStrongObjectPtr<UGameplaySubSystemBase>> SubSystemMap;
};

AddSubSystem 在加入容器后,会同时调用 AddReplicatedSubSystem,把支持同步的 SubSystem 注册到宿主的 RegisteredSubObjectList:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void FGameplaySubSystemCollectionBase::AddSubSystem(UGameplaySubSystemBase* SubSystem)
{
if (!IsValid(SubSystem)) return;

// 如果原本已经有了,则直接替换一个新的
if (auto CurrentSubSystem = GetSubSystemInternal(SubSystem->GetClass()); IsValid(CurrentSubSystem))
{
RemoveSubSystem(CurrentSubSystem);
}

SubSystemMap.Add(SubSystem->GetClass(), TStrongObjectPtr(SubSystem));
SubSystem->Initialize();

AddReplicatedSubSystem(SubSystem);
}

void FGameplaySubSystemCollectionBase::RemoveSubSystem(UGameplaySubSystemBase* SubSystem)
{
if (!IsValid(SubSystem)) return;

auto SubSystemClass = SubSystem->GetClass();
if (!SubSystemMap.Contains(SubSystemClass) || SubSystemMap.FindRef(SubSystemClass).Get() != SubSystem) return;

SubSystem->Uninitialize();
RemoveReplicatedSubSystem(SubSystem);

SubSystemMap.Remove(SubSystemClass);
SubSystem->ConditionalBeginDestroy();
SubSystem->MarkAsGarbage();
}

Get 现在同时提供运行时 UClass* 版本(用于动态 / 蓝图 / Lua 调用)和模板版本(编译期类型安全):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
template<typename TBaseType>
struct FGameplaySubSystemCollection : FGameplaySubSystemCollectionBase
{
static_assert(TIsDerivedFrom<TBaseType, UGameplaySubSystemBase>::Value, "TBaseType must inherit from UGameplaySubSystemBase");

FGameplaySubSystemCollection() : FGameplaySubSystemCollectionBase(TBaseType::StaticClass()) {}

TBaseType* GetSubSystem(UClass* SubSystemClass) const
{
return static_cast<TBaseType*>(GetSubSystemInternal(SubSystemClass));
}

template<class TSubSystemClass = TBaseType>
requires (TIsDerivedFrom<TSubSystemClass, TBaseType>::Value == true)
TSubSystemClass* GetSubSystem() const
{
return static_cast<TSubSystemClass*>(GetSubSystemInternal(TSubSystemClass::StaticClass()));
}

TArray<TBaseType*> GetSubSystems(UClass* SubSystemClass = nullptr) const
{
const TArray<UGameplaySubSystemBase*>& Array = GetSubSystemsInternal(SubSystemClass);
const TArray<TBaseType*>* SpecificArray = reinterpret_cast<const TArray<TBaseType*>*>(&Array);
return *SpecificArray;
}

template<class TSubSystemClass = TBaseType>
requires (TIsDerivedFrom<TSubSystemClass, TBaseType>::Value == true)
TArray<TSubSystemClass*> GetSubSystems() const
{
const TArray<UGameplaySubSystemBase*>& Array = GetSubSystemsInternal(TSubSystemClass::StaticClass());
const TArray<TSubSystemClass*>* SpecificArray = reinterpret_cast<const TArray<TSubSystemClass*>*>(&Array);
return *SpecificArray;
}
};

特别地,FGameplaySubSystemCollection::GetSubSystems 由于 GetSubSystemsInternal 返回的也是 UGameplaySubSystemBase* 指针,内存大小和 TSubSystemClass* 指针一样,所以可以使用 reinterpret_cast 直接将整个数组的类型转化,节省遍历 cast 开销。

GetSubSystemsInternal 在内部还做了 IsChildOf 过滤,传入基类时自动收集所有派生子系统:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
TArray<UGameplaySubSystemBase*> FGameplaySubSystemCollectionBase::GetSubSystemsInternal(UClass* SubSystemClass) const
{
if (SubSystemClass == nullptr)
SubSystemClass = BaseType;

TArray<UGameplaySubSystemBase*> OutArray;
for (auto& [Class, SubSystem] : SubSystemMap)
{
if (!IsValid(Class) || !SubSystem.IsValid()) continue;
if (Class == SubSystemClass || Class->IsChildOf(SubSystemClass))
{
OutArray.Add(SubSystem.Get());
}
}
return OutArray;
}

SubSystemBase

需要一个 SubSystemBase。

提供一些基础的方法,Initialize、Uninitialize、Tick 在 SubSystemCollection 中调用。

同时子类只需要关心:OnInitialized、OnUninitialized、OnTick。

对于各自的业务,各自继承自定义的 SubSystemBase ,然后再自定义各自的 SubSystem 继承于这个业务扩展出来的 SubSystemBase 即可。

SubSystemBase->GetOuter() 就可以拿到对应的 Manager。

对于 Tick ,维护一个 LastTickTimeStamp,用于计算 DeltaTime,并且只在 Standalone / DS 上触发 OnTick,避免客户端走重复的业务逻辑:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// GameplaySubSystemBase.h

UCLASS(Abstract)
class GAMEPLAYSUBSYSTEM_API UGameplaySubSystemBase : public UObject, public IInterface_ActorSubobject
{
GENERATED_BODY()

#pragma region Init

public:
void Initialize();
void Uninitialize();

protected:
virtual void OnInitialized();
virtual void OnUninitialized();

#pragma endregion Init


#pragma region Tick

public:
void Tick();

protected:
virtual void OnTick(float DeltaTime);

protected:
virtual double GetTickInternal() const;
virtual double GetCurrentTimeStamp() const;

private:
double LastTickTimeStamp = -1.0f;

#pragma endregion Tick


#pragma region Replicate

public:
virtual bool IsSupportedForNetworking() const override { return false; }

public:
AActor* GetOwnerActor() const;
virtual bool CallRemoteFunction(UFunction* Function, void* Parameters, FOutParmRec* OutParams, FFrame* Stack) override;
virtual int32 GetFunctionCallspace(UFunction* Function, FFrame* Stack) override;

public:
virtual void OnCreatedFromReplication() override;
virtual void OnDestroyedFromReplication() override;

bool GetIsCreatedFromReplication() const { return IsCreatedFromReplication; }

private:
UPROPERTY()
bool IsCreatedFromReplication = false;

#pragma endregion Replicate
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// GameplaySubSystemBase.cpp

void UGameplaySubSystemBase::Initialize()
{
LastTickTimeStamp = GetCurrentTimeStamp();
OnInitialized();
}

void UGameplaySubSystemBase::Tick()
{
if (!UKismetSystemLibrary::IsStandaloneOrDS(this)) return;
auto TickInternal = GetTickInternal();
if (TickInternal < 0) return;

auto CurrentTickTime = GetCurrentTimeStamp();
if (CurrentTickTime - LastTickTimeStamp > TickInternal)
{
OnTick(CurrentTickTime - LastTickTimeStamp);
LastTickTimeStamp = CurrentTickTime;
}
}

double UGameplaySubSystemBase::GetTickInternal() const
{
return -1.0f;
}

double UGameplaySubSystemBase::GetCurrentTimeStamp() const
{
if (!IsValid(GetWorld())) return 0.0f;
AGameStateBase* GS = GetWorld()->GetGameState();
if (!IsValid(GS)) return 0.0f;
return GS->GetServerWorldTimeSeconds();
}

时间戳统一使用 GameState->GetServerWorldTimeSeconds() 而非本地 World->GetTimeSeconds(),可以保证服务端权威时间在双端语义一致,方便同步类的逻辑(如倒计时、能量回复速率)直接用 LastTickTimeStamp 做计算。

同步方案

由于各业务拆分到 SubSystem 中,其中:

  1. SubSystem 需要在 Client 有对应实例;
  2. SubSystem 需要支持属性同步的数据;
  3. SubSystem 需要支持 RPC;

一种简单的方案是将这种需要同步的数据,存储在 Manager 中,SubSystem 也跟着 Manager 创建,但显然这样不够优雅;

于是可以实现一套 SubSystem 的同步方案,核心思路是:

将 SubSystem 作为 Manager 的 SubObject ,通过同步在 Client 创建出来,创建后注册进 Manager 对应的 Collection 中。

同步基建

显然,这里的 Manager 可能是 Actor,也可能是 ActorComponent;

将 SubSystem 作为 Manager 的 SubObject 进行同步创建,UE 中有两条路径可选:

  1. 旧通道:宿主在 ReplicateSubobjects 内主动调用 Channel->ReplicateSubobject(SubSystem, ...) 写入 Bunch;
  2. 新通道(推荐):宿主开启 bReplicateUsingRegisteredSubObjectList = true,把 SubSystem 通过 AddReplicatedSubObject / DestroyReplicatedSubObjectOnRemotePeers 注册到引擎的 RegisteredSubObjectList,由引擎统一驱动;

SubSystem 实现 IInterface_ActorSubobject,在 OnCreatedFromReplication 的回调中通过 GetOuter 获取 Manager;Manager 实现 IGameplaySubSystemCollectionOwnerInterface,从其拿到对应 Collection 并把 SubSystem 注册进去。这样就完成了在 Client 将 SubSystem 注册进对应 Manager 的 Collection。

Create SubObject

flowchart LR
    A[UActorChannel::ProcessBunch] --> B[UActorChannel::ReadContentBlockPayload]
    B --> C[UActorChannel::ReadContentBlockHeader]
    A --> D[UActorChannel::FindOrCreateReplicator]
    A --> E[FObjectReplicator::ReceivedBunch]

在 Client 收到同步包时,首先进行 UActorChannel::ReadContentBlockHeader,在这里会从 Bunch 中反序列出对应的数据,对应着 UActorChannel::WriteContentBlockHeader 中序列化的数据。

可以观察到,对于 SubObj,会在这里进行 NewObject 并且由 ActorChannel->CreateSubObjects 持有;并且最后返回 SubObj 作为 RepObj,在 UActorChannel::ProcessBunch 中 FindOrCreateReplicator 并记录在 ReplicationMap 中,后续进行 FObjectReplicator::ReceivedBunch;在 FObjectReplicator::PostReceivedBunch 中 CallRepNotifies 执行一系列 OnRep。

特别地,如果在一个 Object 中同步了一个 SubObjectArray,该 Array 标记有 ReplicatedUsing 方法,当 SubObject 在 Client 创建出时,会立马调用到该 OnRep 方法。

一致的 Outer

Client 创建出 SubSystem 时,通过 GetOuter 找到 Manager,从而找到 Collection 注册进该 SubSystem;所以需要保证这里 NewObject 时,和 DS 保持一致的 Outer,这样才能找到正确的 Manager。

实际上,在 UE4 中这里 NewObject 时,直接将 Actor 作为 Outer(但 SubObj 可能由 ActorComponent 等 SubObj 持有;错误的 Actor 会丢失索引路由)。

参考 UE5,在 UActorChannel::ReadContentBlockHeader 时新写入一个 Bit(0/1) 表示 bActorIsOuter,仅当 (ObjOuter == Actor) || (!Obj->IsSupportedForNetworking()) 时该值为 true;为了节省流量,仅当 bActorIsOuter = false 时候向 Bunch 中写入 ObjOuter:

1
2
3
4
5
6
7
UObject* ObjOuter = Obj->GetOuter();
const bool bActorIsOuter = (ObjOuter == Actor) || (!Obj->IsSupportedForNetworking());
Bunch.WriteBit(bActorIsOuter ? 1 : 0);
if (!bActorIsOuter)
{
Bunch << ObjOuter;
}

在创建完 SubObj 后,会调用 Actor->OnSubobjectCreatedFromReplication(SubObj),找到对应的 Interface 执行回调:

1
2
3
4
5
6
7
8
if (UActorComponent* Component = Cast<UActorComponent>(NewSubobject))
{
Component->OnCreatedFromReplication();
}
else if (IInterface_ActorSubobject* SubojectInterface = Cast<IInterface_ActorSubobject>(NewSubobject))
{
SubojectInterface->OnCreatedFromReplication();
}

在这里可以进行 SubSystem 的注册。

具体实现

Manager

宿主有两种可选接入方式:

方式一(推荐):开启 bReplicateUsingRegisteredSubObjectList,由引擎自动驱动,宿主无需重载 ReplicateSubobjects:

1
2
3
4
5
// Manager 是 Actor / ActorComponent 都行
AManager::AManager()
{
bReplicateUsingRegisteredSubObjectList = true;
}

AddSubSystem / RemoveSubSystem 时,Collection 会自动调用宿主的 AddReplicatedSubObject / DestroyReplicatedSubObjectOnRemotePeers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void FGameplaySubSystemCollectionBase::AddReplicatedSubSystem(UGameplaySubSystemBase* SubSystem)
{
if (!Outer.IsValid()) return;
if (!IsValid(SubSystem) || SubSystem->IsSupportedForNetworking() == false) return;

if (auto OwnerActor = Cast<AActor>(Outer); IsValid(OwnerActor) && OwnerActor->IsUsingRegisteredSubObjectList())
{
OwnerActor->AddReplicatedSubObject(SubSystem, COND_OwnerOnly);
}

if (auto OwnerActorComponent = Cast<UActorComponent>(Outer); IsValid(OwnerActorComponent) && OwnerActorComponent->IsUsingRegisteredSubObjectList())
{
OwnerActorComponent->AddReplicatedSubObject(SubSystem, COND_OwnerOnly);
}
}

void FGameplaySubSystemCollectionBase::RemoveReplicatedSubSystem(UGameplaySubSystemBase* SubSystem)
{
if (!Outer.IsValid()) return;
if (!IsValid(SubSystem) || SubSystem->IsSupportedForNetworking() == false) return;

if (auto OwnerActor = Cast<AActor>(Outer); IsValid(OwnerActor) && OwnerActor->IsUsingRegisteredSubObjectList())
{
OwnerActor->DestroyReplicatedSubObjectOnRemotePeers(SubSystem);
}

if (auto OwnerActorComponent = Cast<UActorComponent>(Outer); IsValid(OwnerActorComponent) && OwnerActorComponent->IsUsingRegisteredSubObjectList())
{
OwnerActorComponent->DestroyReplicatedSubObjectOnRemotePeers(SubSystem);
}
}

方式二(兼容旧路径):宿主重载 ReplicateSubobjects,调用 Collection 提供的 ReplicateSubSystems:

1
2
3
4
5
6
7
bool UManager::ReplicateSubobjects(UActorChannel* Channel, FOutBunch* Bunch, FReplicationFlags* RepFlags)
{
bool WroteSomething = false;
WroteSomething |= Super::ReplicateSubobjects(Channel, Bunch, RepFlags);
WroteSomething |= SubSystemCollections.ReplicateSubSystems(Channel, Bunch, RepFlags);
return WroteSomething;
}

无论走哪条路径,Manager 都需要实现 IGameplaySubSystemCollectionOwnerInterface,用于后续 SubSystem 的注册:

1
2
3
4
5
// Manager.h
virtual TArray<FGameplaySubSystemCollectionBase*> GetSubSystemCollectionPtrs() override
{
return { &SubSystemCollections };
}

SubSystemCollection

对于 SubSystemCollection,方式二需要的 ReplicateSubSystems 实现,将需要同步的(IsSupportedForNetworking() == true)SubSystem 写入到 Bunch 中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bool FGameplaySubSystemCollectionBase::ReplicateSubSystems(UActorChannel* Channel, FOutBunch* Bunch, FReplicationFlags* RepFlags)
{
if (!Outer.IsValid()) return false;
if (!IsValid(Channel)) return false;

if (RepFlags->bNetInitial) return false;

bool WroteSomething = false;
const auto& SubSystems = GetSubSystems();
for (auto SubSystem : SubSystems)
{
if (!IsValid(SubSystem)) continue;
if (SubSystem->IsSupportedForNetworking())
{
WroteSomething |= Channel->ReplicateSubobject(SubSystem, *Bunch, *RepFlags);
}
}
return WroteSomething;
}

特别地,当 RepFlags 初始化时(bNetInitial),先不进行 SubSystem 的同步。

这是因为在 AActor::ReplicateSubobjects 时,递归进行的 ReplicateSubobjects:

1
2
3
4
5
6
7
8
for (UActorComponent* ActorComp : ReplicatedComponents)
{
if (ActorComp && ActorComp->GetIsReplicated())
{
WroteSomething |= ActorComp->ReplicateSubobjects(Channel, Bunch, RepFlags);
WroteSomething |= Channel->ReplicateSubobject(ActorComp, *Bunch, *RepFlags);
}
}

同步一般会先进行 Actor 的同步,之后进行 ActorComponent 的同步,也就是从上到下的设置同步参数,然后 StartReplicating:

flowchart LR
    A[UActorChannel::ReplicateSubobject]
    --> B[UActorChannel::CreateReplicator]
    --> C[FObjectReplicator::StartReplicating]
    --> D[UNetDriver::GetReplicationChangeListMgr]
    --> E[FRepLayout::CreateReplicationChangelistMgr]

但是如果 SubSystem 作为一个 Manager(ActorComponent) 的 SubSystem 时,由于递归的顺序,会先调用 ActorComponent 的 SubSystem 的 StartReplicating,然后再调用 ActorComponent 的 StartReplicating,可能导致时序问题,所以延迟一帧开始同步 SubSystem(判断 RepFlags->bNetInitial)。

SubSystemBase

首先对于需要同步的 SubSystem,重载 IsSupportedForNetworking 标记为 true;为了在 Client 创建时有回调,需要实现 IInterface_ActorSubobject 接口。

创建后在 Client 正常 GetOuter,就可以获取到 Manager,通过 Manager 的 IGameplaySubSystemCollectionOwnerInterface 实现的 GetSubSystemCollectionPtr 找到对应 Collection,将 SubSystem 注册进去。

同时,为了支持发送 RPC,需要实现 GetOwnerActor 以找到该 SubSystem 所属的 Actor,以作为 ProcessRemoteFunction 的参数;并且需要重载 CallRemoteFunction、GetFunctionCallspace,以进行正常的 RPC。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// GameplaySubSystemBase.cpp

AActor* UGameplaySubSystemBase::GetOwnerActor() const
{
UObject* Outer = GetOuter();
if (!IsValid(Outer)) return nullptr;

if (auto OwnerActor = Cast<AActor>(Outer); IsValid(OwnerActor))
{
return OwnerActor;
}

if (auto OwnerActorComponent = Cast<UActorComponent>(Outer); IsValid(OwnerActorComponent))
{
return OwnerActorComponent->GetOwner();
}

return nullptr;
}

bool UGameplaySubSystemBase::CallRemoteFunction(UFunction* Function, void* Parameters, FOutParmRec* OutParams, FFrame* Stack)
{
bool bProcessed = false;

if (AActor* OwnerActor = GetOwnerActor())
{
FWorldContext* const Context = GEngine->GetWorldContextFromWorld(GetWorld());
if (Context != nullptr)
{
for (FNamedNetDriver& Driver : Context->ActiveNetDrivers)
{
if (Driver.NetDriver != nullptr && Driver.NetDriver->ShouldReplicateFunction(OwnerActor, Function))
{
Driver.NetDriver->ProcessRemoteFunction(OwnerActor, Function, Parameters, OutParams, Stack, this);
bProcessed = true;
}
}
}
}
return bProcessed;
}

int32 UGameplaySubSystemBase::GetFunctionCallspace(UFunction* Function, FFrame* Stack)
{
UObject* Outer = GetOuter();
if (!IsValid(Outer)) return false;
return Outer->GetFunctionCallspace(Function, Stack);
}

void UGameplaySubSystemBase::OnCreatedFromReplication()
{
IsCreatedFromReplication = true;

auto CollectionOwner = Cast<IGameplaySubSystemCollectionOwnerInterface>(GetOuter());
if (CollectionOwner == nullptr) return;

auto CollectionPtr = CollectionOwner->GetSubSystemCollectionPtr(GetClass());
if (CollectionPtr == nullptr) return;

CollectionPtr->SetOuter(GetOuter());
CollectionPtr->AddSubSystem(this);

CollectionPtr->OnCreatedFromReplication.Broadcast(GetClass(), this);
}

void UGameplaySubSystemBase::OnDestroyedFromReplication()
{
auto CollectionOwner = Cast<IGameplaySubSystemCollectionOwnerInterface>(GetOuter());
if (CollectionOwner == nullptr) return;

auto CollectionPtr = CollectionOwner->GetSubSystemCollectionPtr(GetClass());
if (CollectionPtr == nullptr) return;

CollectionPtr->RemoveSubSystem(this);
}

OnCreatedFromReplication 在完成注册后会广播 Collection->OnCreatedFromReplication(Class, Instance),业务侧可以挂载该委托做"等到客户端 SubSystem 就位"的初始化逻辑(例如 UI 绑定)。

IsCreatedFromReplication 字段记录 SubSystem 是不是由同步路径创建的,可用于子类区分"本地直接 New 出来的 server 端实例"和"客户端从同步包反序列化出来的实例"。

这样,对于一个 SubSystem 就可以正常的进行数据同步与 RPC 。

Note

Destroy

在 UObject::ConditionalBeginDestroy 执行到 UActorChannel::CleanUp 时,会清除 Channel 中所有的 SubObj。

此时需要注意 GC 的时序,有可能此时 Actor->GetWorld() 中 Actor->GetOuter() 已经提前被清除,导致无法进行 DestroyActorAndComponents,无法正确清除 CreateSubObjects:

1
2
3
4
5
if (!Actor->bNetTemporary && Actor->GetWorld() != NULL && !IsEngineExitRequested() && Connection->Driver->ShouldClientDestroyActor(Actor))
{
UE_LOG(LogNetDormancy, Verbose, TEXT("UActorChannel::CleanUp: Destroying Actor. %s"), *Describe());
DestroyActorAndComponents();
}
RPC

在 UE4 中,如果在 ThisClass->UObject 这一条继承链中,没有任何一个 UPROPERTY 属性,则相关 UFUNCTION 的同步数据无法写入 NetField,无法发送 RPC。

这是因为在 UNetDriver::InternalProcessRemoteFunctionPrivate 时调用的 const FClassNetCache* ClassCache = NetCache->GetClassNetCache(TargetObj->GetClass());其中 UClass::SetUpRuntimeReplicationData 判定了:

1
if (!HasAnyClassFlags(CLASS_ReplicationDataIsSetUp) && PropertyLink != NULL)

这里判断了 PropertyLink != nullptr,不过显然是没有必要的,可以将其直接去掉,这样就支持了没有 UPROPERTY 的 Object 可以正常 SetUpRuntimeReplicationData。

该问题在 UE5.3 中正式修复:Allow replication of UObjects with UFunctions but no UProperties。